/*
 * 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙，邂逅框架梦]
 * 
 * https://zhiqim.org/project/zhiqim_components/zhiqim_manager.htm
 *
 * Zhiqim Manager is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */
package org.zhiqim.manager.presenter;

import java.util.List;

import org.zhiqim.httpd.HttpRequest;
import org.zhiqim.httpd.context.annotation.AnIntercept;
import org.zhiqim.httpd.validate.ones.IsNotEmpty;
import org.zhiqim.kernel.annotation.AnAlias;
import org.zhiqim.kernel.json.Jsons;
import org.zhiqim.kernel.util.Arrays;
import org.zhiqim.kernel.util.Lists;
import org.zhiqim.kernel.util.Validates;
import org.zhiqim.manager.ZmrConstants;
import org.zhiqim.manager.ZmrSessionUser;
import org.zhiqim.manager.dao.ZmrOperatorDao;
import org.zhiqim.manager.dbo.ZmrDept;
import org.zhiqim.manager.dbo.ZmrOperator;
import org.zhiqim.orm.ORM;
import org.zhiqim.orm.dbo.Updater;

/**
 * 部门控制器
 *
 * @version v1.0.0 @author zouzhigang 2017-6-6 新建与整理
 */
@AnAlias("ZmrDeptPresenter")
@AnIntercept("chkZmrLogin")
public class ZmrDeptPresenter implements ZmrConstants
{
    /**
     * 在部门成员管理界面中，增加多个部门成员
     * 
     * @param request       请求
     * @throws Exception    异常
     */
    public static void doAddDeptOperator(HttpRequest request) throws Exception
    {
        request.addValidate(new IsNotEmpty("deptId", "请选择一个部门"));
        request.addValidate(new IsNotEmpty("operatorCodes", "请选择操作员"));
        if (!request.chkValidate())
        {
            request.setResponseError(request.getAlertMsg());
            return;
        }
        
        //判断部门是否存在
        long deptId = request.getParameterLong("deptId");
        ZmrDept dept = ORM.table().item(ZmrDept.class, deptId);
        if (dept == null)
        {
            request.returnHistory("您选择的部门不存在，请选择一个有效的部门");
            return;
        }
        
        String operatorCodes = request.getParameter("operatorCodes");
        String[] operatorCodeArr = Arrays.toStringArray(operatorCodes);
        for (String operatorCode : operatorCodeArr)
        {
            ZmrOperator operator = ORM.table().item(ZmrOperator.class, operatorCode);
            if (operator == null)
                continue;
        
            //操作员部门
            String operatorDept = operator.getOperatorDept();
            if (Validates.isEmpty(operatorDept))
                operatorDept = "" + deptId;
            else
                operatorDept += "," + deptId;
            
            //操作员所有部门
            String operatorDeptAll = operator.getOperatorDeptAll();
            if (Validates.isEmpty(operatorDeptAll))
                operatorDeptAll = dept.getDeptParentAll();
            else
                operatorDeptAll += "," + dept.getDeptParentAll();
            operatorDeptAll += "," + operatorDept;
            
            //去重
            operatorDeptAll = Arrays.toFilterSameStr(Arrays.toStringArray(operatorDeptAll));
            
            Updater updater = new Updater();
            updater.addField("operatorDept", operatorDept);
            updater.addField("operatorDeptAll", operatorDeptAll);
            updater.addMust("operatorCode", operatorCode);
            
            ORM.table().update(ZmrOperator.class, updater);
            
            //设置为当前选中
            ZmrSessionUser sessionUser = request.getSessionUser(ZmrSessionUser.class);
            sessionUser.setValue(ZMR_SESSION_USER_DEPT_ID, deptId);
            
            //增加操作日志
            ZmrOperatorDao.addOperateLog(request, "增加部门操作员关联", Jsons.toString("deptId", deptId, "operatorCodes", operatorCodes));
        }
    }
    
    /**
     * 增加操作员多个部门，参数统一在request中
     * 
     * @param request       请求
     * @throws Exception    异常
     */
    public static void doAddOperatorDepts(HttpRequest request) throws Exception
    {
        request.addValidate(new IsNotEmpty("operatorCode", "请选择操作员"));
        request.addValidate(new IsNotEmpty("deptIds", "请选择一个部门"));
        if (!request.chkValidate())
        {
            request.setResponseError(request.getAlertMsg());
            return;
        }
        
        //判断操作员是否存在
        String operatorCode = request.getParameter("operatorCode");
        ZmrOperator operator = ORM.table().item(ZmrOperator.class, operatorCode);
        if (operator == null)
        {
            request.returnHistory("您选择的操作员不存在，请选择一个有效的操作员");
            return;
        }
        
        //判断部门是否存在
        long[] deptIdArr = Arrays.toLongArray(request.getParameter("deptIds"));
        for (long deptId : deptIdArr)
        {
            ZmrDept dept = ORM.table().item(ZmrDept.class, deptId);
            if (operator == null)
                continue;
        
            //操作员部门
            if (Validates.isEmpty(operator.getOperatorDept()))
                operator.setOperatorDept("" + deptId);
            else
                operator.setOperatorDept(operator.getOperatorDept() + "," + deptId);
            
            //操作员所有部门
            String operatorDeptAll = operator.getOperatorDeptAll();
            if (Validates.isEmpty(operatorDeptAll))
                operatorDeptAll = dept.getDeptParentAll();
            else
                operatorDeptAll += "," + dept.getDeptParentAll();
            operatorDeptAll += "," + operator.getOperatorDept();
            operator.setOperatorDeptAll(operatorDeptAll);
        }
        
        Updater updater = new Updater();
        updater.addField("operatorDept", operator.getOperatorDept());
        updater.addField("operatorDeptAll", Arrays.toFilterSameStr(operator.getOperatorDeptAll()));
        updater.addMust("operatorCode", operatorCode);
        
        ORM.table().update(ZmrOperator.class, updater);
    }
    
    /**
     * 删除操作员部门，参数统一在request中
     * 
     * @param request       请求
     * @throws Exception    异常
     */
    public static void doDeleteOperatorDept(HttpRequest request) throws Exception
    {
        request.addValidate(new IsNotEmpty("operatorCode", "请选择一个操作员"));
        request.addValidate(new IsNotEmpty("deptId", "请选择一个部门"));
        if (!request.chkValidate())
        {
            request.setResponseError(request.getAlertMsg());
            return;
        }
        
        String operatorCode = request.getParameter("operatorCode");
        ZmrOperator operator = ORM.table().item(ZmrOperator.class, operatorCode);
        if (operator == null)
        {
            request.setResponseError("请选择一个有效的操作员");
            return;
        }
        
        //删除对应的部门
        long deptId = request.getParameterLong("deptId");
        String operatorDept = operator.getOperatorDept();
        List<Long> operatorDeptList = Lists.toLongList(operatorDept);
        operatorDeptList.remove(deptId);
        
        operatorDept = Lists.toString(operatorDeptList);
        
        //重置所有部门
        String operatorDeptAll = null;
        for (long oprDeptId : operatorDeptList)
        {
            ZmrDept dept = ORM.table().item(ZmrDept.class, oprDeptId);
            if (dept == null)
                continue;
            
            if (operatorDeptAll == null)
                operatorDeptAll = dept.getDeptParentAll();
            else
                operatorDeptAll += "," + dept.getDeptParentAll();
            
            operatorDeptAll += "," + oprDeptId;
        }
        operatorDeptAll = Arrays.toFilterSameStr(operatorDeptAll);
        
        Updater updater = new Updater();
        updater.addField("operatorDept", operatorDept);
        updater.addField("operatorDeptAll", operatorDeptAll);
        updater.addMust("operatorCode", operatorCode);
        
        ORM.table().update(ZmrOperator.class, updater);
        
        //增加操作日志
        ZmrOperatorDao.addOperateLog(request, "取消部门操作员关联", Jsons.toString("deptId", deptId, "operatorCode", operatorCode));
    }
    
}
